<script setup lang="ts">
import { Settings24Regular as SettingsIcon } from '@vicons/fluent'
import { useMagicKeys, whenever } from '@vueuse/core'
import { useMessage } from 'naive-ui'

const { t } = useI18n()
const message = useMessage()
const showConfigModal = ref(false)
const loading = ref(false)
const error = ref<string | null>(null)

// 配置数据
const config = ref({
  providers: {
    local: {
      type: 'ollama',
      api_url: 'http://192.168.1.5:11434',
      chat_endpoint: '/v1/chat/completions',
      models_endpoint: '/api/tags',
      model: 'qwen7b:latest'
    },
    deepseek: {
      type: 'openai',
      api_url: 'https://api.deepseek.com',
      chat_endpoint: '/v1/chat/completions',
      models_endpoint: '/api/tags',
      model: 'deepseek-chat',
      api_key: 'sk-38c4020d709a420bb61e7ad22f8aacea'
    }
  },
  current_provider: 'deepseek',
  temperature: 0.1,
  top_p: 0.7,
  max_tokens: 2048,
  frequency_penalty: 0.0,
  presence_penalty: 0.0,
  repeat_penalty: 1.0,
  stream: true,
  timeout: 300,
  proxy: null,
  safe_mode: true,
  input_encoding: 'auto'
})

// 加载配置
const loadConfig = async () => {
  loading.value = true
  error.value = null
  
  try {
    const response = await fetch('/api/config')
    if (response.ok) {
      const result = await response.json()
      if (result.status === 'success') {
        config.value = result.data
      } else {
        error.value = result.message || '加载配置失败'
        message.error(result.message || '加载配置失败')
      }
    } else {
      error.value = `HTTP ${response.status}: ${response.statusText}`
      message.error(`加载配置失败: HTTP ${response.status}`)
    }
  } catch (err) {
    error.value = err instanceof Error ? err.message : '网络错误'
    message.error('加载配置失败')
  } finally {
    loading.value = false
  }
}

// 保存配置
const saveConfig = async () => {
  loading.value = true
  error.value = null
  
  try {
    const response = await fetch('/api/config', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(config.value)
    })
    
    const result = await response.json()
    if (response.ok && result.status === 'success') {
      message.success('配置保存成功')
      showConfigModal.value = false
    } else {
      error.value = result.message || '保存配置失败'
      message.error(result.message || '保存配置失败')
    }
  } catch (err) {
    error.value = err instanceof Error ? err.message : '网络错误'
    message.error('保存配置失败')
  } finally {
    loading.value = false
  }
}

// 测试配置
const testConfig = async () => {
  loading.value = true
  error.value = null
  
  try {
    const response = await fetch('/api/config/test', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(config.value)
    })
    
    const result = await response.json()
    if (response.ok && result.status === 'success') {
      message.success(`配置测试成功 - ${result.provider}: ${result.model}`)
    } else {
      message.error(result.message || '配置测试失败')
    }
  } catch (err) {
    message.error('配置测试失败')
  } finally {
    loading.value = false
  }
}

// 重置配置
const resetConfig = () => {
  loadConfig()
}

// 快捷键支持
const { ctrl_comma } = useMagicKeys({
  passive: false,
  onEventFired(e) {
    if (e.ctrlKey && e.key === ',' && e.type === 'keydown') e.preventDefault()
  },
})
whenever(ctrl_comma, () => showConfigModal.value = true)

// 组件挂载时加载配置
onMounted(() => {
  loadConfig()
})
</script>

<template>
  <div class="hidden md:block md:me-2">
    <n-button 
      @click="showConfigModal = true"
      quaternary
      circle
      :title="t('common.settings')"
    >
      <template #icon>
        <n-icon :component="SettingsIcon" />
      </template>
    </n-button>

    <!-- 配置对话框 -->
    <n-modal v-model:show="showConfigModal" preset="dialog" title="AI配置" size="huge">
      <div v-if="loading" class="flex justify-center items-center py-8">
        <n-spin size="large" />
      </div>
      
      <div v-else-if="error" class="text-center py-8 text-red-500">
        <n-alert type="error" :title="error" />
      </div>

      <n-form v-else :model="config" label-placement="left" label-width="120px">
        <n-tabs type="line" animated>
          <!-- 提供商配置 -->
          <n-tab-pane name="providers" tab="提供商配置">
            <n-form-item label="当前提供商">
              <n-select v-model:value="config.current_provider" :options="[
                { label: '本地 (Ollama)', value: 'local' },
                { label: 'DeepSeek', value: 'deepseek' }
              ]" />
            </n-form-item>

            <!-- 本地配置 -->
            <n-card title="本地配置 (Ollama)" v-if="config.current_provider === 'local'">
              <n-form-item label="API地址">
                <n-input v-model:value="config.providers.local.api_url" placeholder="http://localhost:11434" />
              </n-form-item>
              <n-form-item label="聊天端点">
                <n-input v-model:value="config.providers.local.chat_endpoint" placeholder="/v1/chat/completions" />
              </n-form-item>
              <n-form-item label="模型端点">
                <n-input v-model:value="config.providers.local.models_endpoint" placeholder="/api/tags" />
              </n-form-item>
              <n-form-item label="模型名称">
                <n-input v-model:value="config.providers.local.model" placeholder="qwen7b:latest" />
              </n-form-item>
            </n-card>

            <!-- DeepSeek配置 -->
            <n-card title="DeepSeek配置" v-if="config.current_provider === 'deepseek'">
              <n-form-item label="API地址">
                <n-input v-model:value="config.providers.deepseek.api_url" placeholder="https://api.deepseek.com" />
              </n-form-item>
              <n-form-item label="API密钥">
                <n-input v-model:value="config.providers.deepseek.api_key" type="password" show-password-on="click" />
              </n-form-item>
              <n-form-item label="聊天端点">
                <n-input v-model:value="config.providers.deepseek.chat_endpoint" placeholder="/v1/chat/completions" />
              </n-form-item>
              <n-form-item label="模型端点">
                <n-input v-model:value="config.providers.deepseek.models_endpoint" placeholder="/api/tags" />
              </n-form-item>
              <n-form-item label="模型名称">
                <n-input v-model:value="config.providers.deepseek.model" placeholder="deepseek-chat" />
              </n-form-item>
            </n-card>
          </n-tab-pane>

          <!-- 模型参数 -->
          <n-tab-pane name="parameters" tab="模型参数">
            <n-form-item label="温度">
              <n-slider v-model:value="config.temperature" :min="0" :max="2" :step="0.1" />
              <span class="ml-2">{{ config.temperature }}</span>
            </n-form-item>
            <n-form-item label="Top P">
              <n-slider v-model:value="config.top_p" :min="0" :max="1" :step="0.1" />
              <span class="ml-2">{{ config.top_p }}</span>
            </n-form-item>
            <n-form-item label="最大令牌数">
              <n-input-number v-model:value="config.max_tokens" :min="1" :max="8192" />
            </n-form-item>
            <n-form-item label="频率惩罚">
              <n-slider v-model:value="config.frequency_penalty" :min="-2" :max="2" :step="0.1" />
              <span class="ml-2">{{ config.frequency_penalty }}</span>
            </n-form-item>
            <n-form-item label="存在惩罚">
              <n-slider v-model:value="config.presence_penalty" :min="-2" :max="2" :step="0.1" />
              <span class="ml-2">{{ config.presence_penalty }}</span>
            </n-form-item>
            <n-form-item label="重复惩罚">
              <n-slider v-model:value="config.repeat_penalty" :min="0.1" :max="2" :step="0.1" />
              <span class="ml-2">{{ config.repeat_penalty }}</span>
            </n-form-item>
          </n-tab-pane>

          <!-- 高级设置 -->
          <n-tab-pane name="advanced" tab="高级设置">
            <n-form-item label="流式输出">
              <n-switch v-model:value="config.stream" />
            </n-form-item>
            <n-form-item label="超时时间(秒)">
              <n-input-number v-model:value="config.timeout" :min="10" :max="600" />
            </n-form-item>
            <n-form-item label="代理设置">
              <n-input v-model:value="config.proxy" placeholder="http://proxy:port" />
            </n-form-item>
            <n-form-item label="安全模式">
              <n-switch v-model:value="config.safe_mode" />
            </n-form-item>
            <n-form-item label="输入编码">
              <n-select v-model:value="config.input_encoding" :options="[
                { label: '自动', value: 'auto' },
                { label: 'UTF-8', value: 'utf-8' },
                { label: 'GBK', value: 'gbk' }
              ]" />
            </n-form-item>
          </n-tab-pane>
        </n-tabs>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="resetConfig" :loading="loading">重置</n-button>
          <n-button @click="testConfig" :loading="loading">测试</n-button>
          <n-button @click="showConfigModal = false">取消</n-button>
          <n-button type="primary" @click="saveConfig" :loading="loading">保存</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<style scoped lang="scss">
.ml-2 {
  margin-left: 8px;
}
</style>
